const express = require('express');    // 框架主体
const body = require('body-parser');    // 接收普通POST数据
const multer = require('multer');    // 接收文件POST数据
const sq = require('mysql');

// 连接数据库
let db = sq.createPool({host: 'localhost', port: 3306, user: 'root', password: 'root', database: 'drag'})

// 创建一个服务
let server = express();
server.listen(8080);

// 添加中间件
server.use(body.urlencoded({extended:false}));
let multerObj = multer({dest: './upload'});
server.use(multerObj.any());

// 接收请求
server.use('/api', (request, response) => {
	if (request.headers['origin'] == 'null' || request.headers['origin'].startsWith('http://localhost')) {
		response.setHeader('Access-Control-Allow-Origin', '*');
	}

	if (request.files) {
		let arr = [];
		request.files.forEach(file => {
			arr.push(`('${file.originalname}','${file.filename}', ${Math.floor(Date.now() / 1000)})`);
		});
	
		// VALUES一次传多个值必须是：VALUES(...),(...)
		let sql = `INSERT INTO drag_table (originalname,filename,time) VALUES${arr.join(',')}`;
		
		// INSERT INTO drag_table (originalname,filename,time) VALUES('123.jpg','21011365a9161d73d0b69cdb6193665b', 1518312761),('456.jpg','4c166d7d43112dfc55d2a7b30dd71db5', 1518312761),('0.jpg','dac687ca5d4a4a130a970d630a5686bf', 1518312761)
		console.log(sql);
		db.query(sql, err => {
			if (err) {
				response.send('数据库错误');
			} else {
				response.send('OK');
			}
		});
	} else {
		response.send('OK');
	}

})

server.use(express.static('./www/'));